package com.by.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.by.cart.entity.Cart;
import com.by.cart.entity.CartMYSQL;
import com.by.cart.mapper.CartMYSQLMapper;
import com.by.cart.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class CartServiceImpl implements CartService {
    // Redis中购物车的键前缀（格式：cart:用户ID）
    private static final String CART_PREFIX = "cart:";
    // 购物车过期时间(24小时，单位：小时)
    private static final long CART_EXPIRE_TIME = 24;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Autowired
    CartMYSQLMapper cartMYSQLMapper;


    /**
     * 添加商品到购物车，默认选中状态为true
     */
    @Override
    public void addCart(Long userId, Cart cart) {
        if (Objects.isNull(userId) || Objects.isNull(cart) || Objects.isNull(cart.getSkuId())) {
            throw new IllegalArgumentException("购物车数据不完整（用户ID/商品ID不能为空）");
        }

        String cartKey = getCartKey(userId);
        HashOperations<String, String, Cart> hashOps = redisTemplate.opsForHash();
        String skuId = String.valueOf(cart.getSkuId());

        // 判断商品是否已在购物车中
        Cart existingCart = hashOps.get(cartKey, skuId);
        if (Objects.nonNull(existingCart)) {
            // 已存在：更新数量和选中状态
            int newQuantity = existingCart.getCount() + cart.getCount();
            existingCart.setCount(Math.max(newQuantity, 1));
            // 如果传入的cart指定了选中状态，则更新，否则保持原有状态
            if (cart.isSelected() != existingCart.isSelected()) {
                existingCart.setSelected(cart.isSelected());
            }
            hashOps.put(cartKey, skuId, existingCart);
        } else {
            // 不存在：设置默认值，默认选中状态为true
            cart.setCount(Math.max(cart.getCount(), 1));
            // 如果未指定选中状态，默认为选中
            if (cart.isSelected()) {
                cart.setSelected(true);
            }
            hashOps.put(cartKey, skuId, cart);
        }

        redisTemplate.expire(cartKey, CART_EXPIRE_TIME, TimeUnit.HOURS);
    }


    /**
     * 更新购物车中商品的规格
     */
    @Override
    public void updateCart(Long userId, Long skuId,Long newSkuId) {
        // 参数校验
        if (Objects.isNull(userId) || Objects.isNull(skuId) || Objects.isNull(newSkuId)) {
            throw new IllegalArgumentException("参数非法（用户ID/商品ID/新商品ID不能为空）");
        }

        // 获取购物车key和Redis操作对象
        String cartKey = getCartKey(userId);
        HashOperations<String, String, Cart> hashOps = redisTemplate.opsForHash();

        // 获取原商品信息
        String skuIdStr = String.valueOf(skuId);
        Cart cart = hashOps.get(cartKey, skuIdStr);


        // 更新商品SKU ID
        cart.setSkuId(newSkuId);

        // 更新购物车
        hashOps.put(cartKey, newSkuId.toString(), cart);

        // 删除旧商品
        hashOps.delete(cartKey, skuIdStr);

        // 重置购物车过期时间
        redisTemplate.expire(cartKey, CART_EXPIRE_TIME, TimeUnit.HOURS);
    }


    /**
     * 新增方法：更新购物车商品的选中状态
     */
    public void updateCartSelection(Long userId, Long skuId, boolean selected) {
        if (Objects.isNull(userId) || Objects.isNull(skuId)) {
            throw new IllegalArgumentException("用户ID/商品ID不能为空");
        }

        String cartKey = getCartKey(userId);
        HashOperations<String, String, Cart> hashOps = redisTemplate.opsForHash();
        String productIdStr = String.valueOf(skuId);

        Cart cart = hashOps.get(cartKey, productIdStr);
        if (Objects.nonNull(cart) && cart.isSelected() != selected) {
            cart.setSelected(selected);
            hashOps.put(cartKey, productIdStr, cart);
            redisTemplate.expire(cartKey, CART_EXPIRE_TIME, TimeUnit.HOURS);
        }
    }

    /**
     * 新增方法：全选/取消全选购物车商品
     */
    public void selectAll(Long userId, boolean selected) {
        if (Objects.isNull(userId)) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        String cartKey = getCartKey(userId);
        HashOperations<String, String, Cart> hashOps = redisTemplate.opsForHash();

        Collection<Cart> carts = hashOps.values(cartKey);
        if (!CollectionUtils.isEmpty(carts)) {
            for (Cart cart : carts) {
                if (cart.isSelected() != selected) {
                    cart.setSelected(selected);
                    hashOps.put(cartKey, String.valueOf(cart.getSkuId()), cart);
                }
            }
            redisTemplate.expire(cartKey, CART_EXPIRE_TIME, TimeUnit.HOURS);
        }
    }


    /**
     * 从购物车中删除单个商品
     */
    @Override
    public void removeCart(Long userId, Long skuId) {
        if (Objects.isNull(userId) || Objects.isNull(skuId)) {
            throw new IllegalArgumentException("用户ID/商品ID不能为空");
        }

        String cartKey = getCartKey(userId);
        HashOperations<String, String, Cart> hashOps = redisTemplate.opsForHash();
        String productIdStr = String.valueOf(skuId);

        hashOps.delete(cartKey, productIdStr);

        // 检查购物车是否为空，为空则删除外层Key
        Long remainingCount = hashOps.size(cartKey);
        if (Objects.nonNull(remainingCount) && remainingCount == 0) {
            redisTemplate.delete(cartKey);
        }
    }


    /**
     * 清空当前用户的所有购物车商品
     */
    @Override
    public void clearCart(Long userId) {
        if (Objects.isNull(userId)) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        String cartKey = getCartKey(userId);
        redisTemplate.delete(cartKey);
    }


    /**
     * 查询当前用户的所有购物车商品，包含选中状态
     */
    @Override
    public List<Cart> getCarts(Long userId) {
        // 验证用户ID
        if (Objects.isNull(userId)) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        String cartKey = getCartKey(userId);
        HashOperations<String, String, Cart> hashOps = redisTemplate.opsForHash();

        // 从Redis获取购物车数据
        List<Cart> cartList = new ArrayList<>(hashOps.values(cartKey));

        // 如果Redis中没有数据，则从MySQL加载并同步到Redis
        if (cartList.isEmpty()) {
            // 从数据库查询
            List<CartMYSQL> mysqlCarts = cartMYSQLMapper.selectByUserId(userId);
            if (!mysqlCarts.isEmpty()) {
                // 转换为Cart对象并添加到列表
                for (CartMYSQL mysqlCart : mysqlCarts) {
                    Cart cart = convertToCart(mysqlCart);
                    cartList.add(cart);
                    // 同步到Redis
                    hashOps.put(cartKey, String.valueOf(mysqlCart.getSkuId()), cart);
                    cartMYSQLMapper.deleteByUserId(userId);
                }
            }else {
                return Collections.emptyList();
            }

        }

        // 重置购物车过期时间（无论数据来自Redis还是MySQL）
        redisTemplate.expire(cartKey, CART_EXPIRE_TIME, TimeUnit.HOURS);

        return cartList;
    }

    /**
     * 将CartMYSQL对象转换为Cart对象
     */
    private Cart convertToCart(CartMYSQL mysqlCart) {
        Cart cart = new Cart();
        cart.setShopId(mysqlCart.getShopId());
        cart.setSkuId(mysqlCart.getSkuId());
        cart.setCount(mysqlCart.getCount());
        cart.setSelected(mysqlCart.getSelected() == 1);
        return cart;
    }

    /**
     * 获取购物车中商品的数量
     */
    @Override
    public int getCartnum(Long userId) {
        if (Objects.isNull(userId))
            throw new IllegalArgumentException("用户ID不能为空");
        String cartKey = getCartKey(userId);
        HashOperations<String, String, Cart> hashOps = redisTemplate.opsForHash();

        return hashOps.size(cartKey).intValue();
    }

    /**
     * 将购物车数据（包含选中状态）持久化到数据库
     */
    @Override
    public void persistToDatabase(Long userId) {
        if (Objects.isNull(userId)) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        List<Cart> cartList = getCarts(userId);


        for (Cart cart : cartList) {
            CartMYSQL cartMYSQL = new CartMYSQL();
            cartMYSQL.setUserId(userId);
            cartMYSQL.setShopId(cart.getShopId());
            cartMYSQL.setSkuId(cart.getSkuId());
            cartMYSQL.setCount(cart.getCount());
            cartMYSQL.setSelected(cart.isSelected()?1:0);


            cartMYSQLMapper.insert(cartMYSQL);
        }

    }

    /**
     * 获取购物车中选中的商品
     * @param userId
     * @return
     */
    @Override
    public List<Cart> getSelectedCarts(Long userId) {
        if (Objects.isNull(userId)) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        String cartKey = "cart:" + userId;

        // 1. 获取该用户所有购物车商品
        List<Cart> carts = getCarts(userId);

        // 2. 筛选出选中的商品
        List<Cart> selectedCarts = new ArrayList<>();
        for (Cart cart : carts) {
            // 只保留选中状态的商品
            if (cart != null && cart.isSelected()) {
                selectedCarts.add(cart);
            }
        }

        return selectedCarts;
    }


    /**
     * 删除购物车中选中的商品
     * @param skuIds
     */
    @Override
    public void removeSelectedCarts(Long userId,List<Long> skuIds) {
        if (Objects.isNull(skuIds) || skuIds.isEmpty())
            throw new IllegalArgumentException("商品ID不能为空");
        for (Long skuId : skuIds) {
            removeCart(userId,skuId);
        }
    }

    // 生成用户购物车的Redis Key
    private String getCartKey(Long userId) {
        return CART_PREFIX + userId;
    }
}
